const path = require('path');
const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const koaStatic = require('koa-static');
const session = require('koa-generic-session');
const redisStore = require('koa-redis');
const { REDIS_CONF } = require('./conf/db');
const { isProd } = require('./utils/env');
const { SESSION_SECRET_KEY } = require('./conf/secretKeys');

const userApiRouter = require('./routes/api/user');
const userViewRouter = require('./routes/views/user');
const utilsApiRouter = require('./routes/api/utils');
const blogViewRouter = require('./routes/views/blog');
const blogHomeApiRouter = require('./routes/api/blog-home');
const profileApiRouter = require('./routes/api/blog-profile'); 

const errorViewRouter = require('./routes/views/error');

// error handler
let onerrorConf = {};
if (isProd) { 
    onerrorConf = {
        redirect: '/error',
    };
}
onerror(app, onerrorConf);

// middlewares
app.use(
    bodyparser({
        enableTypes: ['json', 'form', 'text'],
    })
);
app.use(json());
app.use(logger());
app.use(koaStatic(__dirname + '/public'));
app.use(koaStatic(path.join(__dirname, '..', 'uploadFiles')));

app.use(
    views(__dirname + '/views', {
        extension: 'ejs',
    })
);
//session 配置
app.keys = [SESSION_SECRET_KEY];
app.use(
    session({
        key: 'weibo.sid', //cookie name 默认名
        prefix: 'weibo:sess:', //redis key 前缀
        cookie: {
            path: '/',
            httpOnly: true,
            maxAge: 24 * 60 * 60 * 1000, //ms
        },
        store: redisStore({
            all: `${REDIS_CONF.host}:${REDIS_CONF.port}`,
        }),
    })
);

// logger
app.use(async (ctx, next) => {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(userApiRouter.routes(), userApiRouter.allowedMethods());
app.use(userViewRouter.routes(), userViewRouter.allowedMethods());
app.use(utilsApiRouter.routes(), utilsApiRouter.allowedMethods());
app.use(blogViewRouter.routes(), blogViewRouter.allowedMethods());
app.use(blogHomeApiRouter.routes(), blogHomeApiRouter.allowedMethods());
app.use(profileApiRouter.routes(), profileApiRouter.allowedMethods());

//err路由要写最后
app.use(errorViewRouter.routes(), errorViewRouter.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx);
});

module.exports = app;
